// Package open_browser_plugin
// This plugin can open a browser page when framework boot up

package open_browser_plugin

import (
	"fmt"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"github.com/google/uuid"
	"os/exec"
	"runtime"
	"strings"
)

type Runner struct {
	types.ApplicationRunner `order:"999"`
	Config                  *Config
}

func (r *Runner) Bean() string {
	return "open_browser:runner@" + uuid.New().String()
}

func NewRunner() *Runner {
	return &Runner{}
}

func (r *Runner) Run() error {
	if r.Config.Enable {
		return Open(r.Config.URL)
	}
	return nil
}

var commands = map[string][]string{
	"windows": {"cmd", "/c start"},
	"darwin":  {"open"},
	"linux":   {"bash", "xdg-open"},
}

func Open(uri string) error {
	run, ok := commands[runtime.GOOS]
	program := run[0]
	args := append(run[1:], uri)
	if !ok {
		return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS)
	}

	cmd := exec.Command(program, strings.Join(args, " "))
	return cmd.Start()
}
